package com.gary.lockDemo;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author peng_rui
 * @date 2022/3/17
 */
class MyCache {
    private Map<String, String> cacheMap = new HashMap<>();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void write(String key, String value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在写" + key);
            try {
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cacheMap.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写" + key + "结束");
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void read(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读" + key);
            try {
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = cacheMap.get(key);
            System.out.println(Thread.currentThread().getName() + "读" + key + " : " + value + "完成");
        } finally {
            lock.readLock().unlock();
        }
    }
}
public class LReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            final String num = String.valueOf(i);
            new Thread(() -> {
                myCache.write(num, num);
            }, "写线程"+i).start();
        }

        for (int i = 0; i < 5; i++) {
            final String num = String.valueOf(i);
            new Thread(() -> {
                myCache.read(num);
            }, "读线程"+i).start();
        }
    }
}
